﻿using io.rong;
using Microsoft.AspNet.Hosting;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace Sino.CapacityCloud.Services
{

    public class ChattingService
        : ConfigurableServiceBase, IChattingService
    {

        private readonly string APP_KEY;
        private readonly string APP_SECRET;

        private readonly ILogger _logger;

        public ChattingService(IHostingEnvironment env, ILoggerFactory loggerFactory)
            : base(env, section: "Data:DefaultConnection:RongIoConnection")
        {
            this.APP_KEY = this.Configuration["AppKey"];
            this.APP_SECRET = this.Configuration["AppSecret"];

            this._logger = loggerFactory.CreateLogger<ChattingService>();

            this.RefreshUserInfoAsync("System", "系统消息", "https://obxvr4ieq.qnssl.com/SystemAvatar.png");
        }

        public async Task<string> GenerateTokenAsync(string userId, string name, string portraitUri)
        {
            this._logger.LogInformation($"Calling GenerateTokenAsync with userId={userId}, name={name}, portraitUri={portraitUri}.");
            var result = await RongCloudServer.GetTokenAsync(APP_KEY, APP_SECRET, userId, name, portraitUri);
            var json = JObject.Parse(result);
            int code = (int)json["code"];
            if (code == 200)
            {
                return await Task.FromResult((string)json["token"]);
            }
            else
            {
                throw new InvalidOperationException((string)json["errorMessage"]);
            }
        }

        public async Task<bool> RefreshUserInfoAsync(string userId, string name, string portraitUri)
        {
            this._logger.LogInformation($"Calling RefreshUserInfoAsync with userId={userId}, name={name}, portraitUri={portraitUri}.");
            var result = await RongCloudServer.RefreshUserInfoAsync(APP_KEY, APP_SECRET, userId, name, portraitUri);
            var json = JObject.Parse(result);
            int code = (int)json["code"];
            if (code == 200)
            {
                return await Task.FromResult(true);
            }
            else
            {
                return await Task.FromResult(false);
            }
        }

    }

}